﻿using System.Collections.Generic;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Grundy.Common;
using Grundy.Entity;
using Grundy.Licensing.Server.Command;
using Grundy.Net;

namespace Grundy.Licensing.Server
{
    public class LicenseServer
    {
        private readonly ServerConfiguration _serverConfiguration;
        private readonly LicenseSessionStore _licenseSessionStore;
        private readonly LicenseServiceFactory _licenseServiceFactory;
        private readonly LicensingStrategyFactory _licensingStrategyFactory;
        private TcpServer _server;

        public LicenseServer(ServerConfiguration serverConfiguration, LicenseSessionStore licenseSessionStore, LicenseServiceFactory licenseServiceFactory, LicensingStrategyFactory licensingStrategyFactory)
        {
            _serverConfiguration = serverConfiguration;
            _licenseSessionStore = licenseSessionStore;
            _licenseServiceFactory = licenseServiceFactory;
            _licensingStrategyFactory = licensingStrategyFactory;
        }

        public void Start()
        {
            _server = new TcpServer(IPAddress.Any, _serverConfiguration.Port, _serverConfiguration.MaximumMessageSize, _licenseServiceFactory.Get());
            _server.Start();
        }

        public void Shutdown()
        {
            if (_server != null && _server.Started)
            {
                _server.Shutdown();
            }
        }

        public void Restart()
        {
            Shutdown();
            Start();
        }

        public int ConnectedSockets
        {
            get
            {
                if (_server == null || !_server.Started)
                    return 0;
                return _server.ConnectedSockets;
            }
        }

        public bool IsStarted 
        {
            get
            {
                if (_server == null)
                    return false;
                return _server.Started;
            }
        }

        public IEnumerable<LicenseData> GetLicensesData()
        {
            return _licenseSessionStore.Licenses;
        }
    }
}